<template>
  <div class="category-setting">
    <el-form :model="categoryForm" label-width="150px" label-position="right" :inline-message="true" ref="categoryFormRef" :rules="categoryFormRules">
      <div class="setting-card">
        <div class="card-header">基本信息</div>
        <div class="card-body">
          <el-form-item label="上级栏目" prop="pid">
            <el-cascader v-model="categoryForm.pid" :options="treeData" :props="treeProps" :show-all-levels="false" popper-class="pid-cascader" placeholder="选择上级栏目" style="width: 240px;">
              <template #default="{data}">
                <p @click="handleChooseParent(data)">{{data.name}}</p>
              </template>
            </el-cascader>
          </el-form-item>
          <el-form-item label="栏目名称" prop="name">
            <el-input v-model="categoryForm.name" style="width: 240px" @blur="handleBlurName" placeholder="请填写栏目名称"></el-input>
          </el-form-item>
          <el-form-item label="栏目路径" prop="uri">
            <el-input v-model="categoryForm.uri" style="width: 240px" placeholder="选择上级和栏目名称后自动填充"></el-input>
          </el-form-item>
          <el-form-item label="栏目类型" prop="type">
            <el-select v-model="categoryForm.type" placeholder="请选择栏目类型" style="width: 240px" @change="handleChangeType">
              <el-option v-for="item in categoryTypeList" :key="item.id" :label="item.dataKey" :value="item.dataValue" />
            </el-select>
          </el-form-item>
          <el-form-item v-if="categoryForm.type == 5 " label="链接地址" prop="link">
            <el-input v-model="categoryForm.link" style="width: 240px" placeholder="请填写链接地址"></el-input>
          </el-form-item>
          <!-- 单页与列表详情类型需要选择审核流 -->
          <el-form-item label="绑定审核流" prop="procdefId" v-if="[1,2].includes(categoryForm.type)">
            <el-select v-model="categoryForm.procdefId" placeholder="请选择流程模型" style="width: 240px" clearable>
              <el-option v-for="item in processList" :key="item.id" :label="item.name" :value="item.processDefinitionId" />
            </el-select>
          </el-form-item>
          <el-form-item label="内容模型" prop="modelId" v-if="[1,2].includes(categoryForm.type)">
            <el-select v-model="categoryForm.modelId" placeholder="请选择内容模型" style="width: 240px" clearable @change="handleChangeModel">
              <el-option v-for="item in modelList" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="内容分类" v-if="contentClasses?.length > 0">
            <el-select v-model="categoryForm.info.class" placeholder="请选择内容分类" style="width: 240px" multiple>
              <el-option v-for="item in contentClasses" :key="item.id" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </div>
      </div>

      <div class="setting-card">
        <div class="card-header">拓展信息</div>
        <div class="card-body">
          <el-form-item label="栏目标签">
            <el-tag v-for="tag in categoryForm.info.tags" :key="tag" closable :disable-transitions="false" @close="handleClose(tag)" style="margin-right: 4px;">{{ tag }}</el-tag>
            <el-input v-if="tagInputVisible" ref="tagInputRef" size="small" v-model="tagInputValue" @keyup.enter="handleTagConfirm" @blur="handleTagConfirm" style="width: 80px;" />
            <el-button v-else size="small" @click="handleTagInput">添加</el-button>
          </el-form-item>
          <!-- 菜单分类与链接不需要模板 -->
          <el-form-item label="头部模板" prop="headTemplate" v-if="![5, 10].includes(categoryForm.type) && categoryForm.id">
            <el-select v-model="categoryForm.headTemplate" placeholder="请选择头部模板" style="width: 240px;" clearable>
              <el-option v-for="item in headTemplateList" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="尾部模板" prop="footTemplate" v-if="![5, 10].includes(categoryForm.type) && categoryForm.id">
            <el-select v-model="categoryForm.footTemplate" placeholder="请选择尾部模板" style="width: 240px;" clearable>
              <el-option v-for="item in footTemplateList" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="页面模板" prop="pageTemplate" v-if="![5,6].includes(categoryForm.type) && categoryForm.id">
            <el-select v-model="categoryForm.pageTemplate" placeholder="请选择页面模板" style="width: 240px;" clearable>
              <el-option v-for="item in pageTemplateList" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="详情模板" prop="detailTemplate" v-if="categoryForm.type === 1 && categoryForm.id">
            <el-select v-model="categoryForm.detailTemplate" placeholder="请选择详情模板" style="width: 240px;" clearable>
              <el-option v-for="item in detailTemplateList" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="栏目副标题" prop="subTitle">
            <el-input v-model="categoryForm.subTitle" style="width: 240px" placeholder="请输入栏目副标题"></el-input>
          </el-form-item>
          <el-form-item label="栏目导读" prop="reading">
            <el-input v-model="categoryForm.reading" style="width: 240px" placeholder="请输入栏目导读"></el-input>
          </el-form-item>
          <el-form-item label="栏目图标" prop="navIcon">
            <div style="width: 450px;">
              <IconSelect v-model:currentIcon="categoryForm.navIcon" />
            </div>
          </el-form-item>
          <el-form-item label="栏目背景图">
            <div class="form-img" @click="handleUpload('backImage')">
              <div class="has-img" v-if="categoryForm.backImage">
                <img :src="categoryForm.backImage" alt="">
                <span @click.stop="handleRemoveImg('backImage')">
                  <el-icon><Delete /></el-icon>
                </span>
              </div>
              <el-icon v-else><Plus /></el-icon>
            </div>
          </el-form-item>
          <el-form-item label="栏目封面">
            <div class="form-img" @click="handleUpload('thumb')">
              <div class="has-img" v-if="categoryForm.thumb">
                <img :src="categoryForm.thumb" alt="">
                <span @click.stop="handleRemoveImg('thumb')">
                  <el-icon><Delete /></el-icon>
                </span>
              </div>
              <el-icon v-else><Plus /></el-icon>
            </div>
          </el-form-item>
        </div>
      </div>

      <div class="setting-card">
        <div class="card-header">高级设置</div>
        <div class="card-body">
          <el-form-item label="调用其他栏目数据">
            <el-cascader v-model="categoryForm.originId" :options="treeData" :props="shadowTreeProps" :show-all-levels="false" clearable popper-class="pid-cascader" placeholder="选择上级栏目" style="width: 240px;">
              <template #default="{data}">
                <p @click="handleChooseOrigin(data)">{{data.name}}</p>
              </template>
            </el-cascader>
          </el-form-item>
          <el-form-item label="栏目主题色">
            <el-color-picker v-model="categoryForm.info.themeColor" />
            <span style="color: #999; font-size: 12px;">{{ categoryForm.info.themeColor ? '' : '（未设置, 默认使用站点主题色' + store.state.site.currentSite?.themeColor + '）' }}</span>
          </el-form-item>
          <!-- 科室设置 -->
          <div class="setting-card" v-if="categoryForm.type == 9">
            <el-form-item label="特色科室">
              <el-checkbox-group v-model="categoryForm.info.specialClass" class="checkbox-wrap">
                <el-checkbox v-for="item in specialDepartList" :key="item.dataValue" :label="item.dataValue">{{item.dataKey}}</el-checkbox>
              </el-checkbox-group> 
            </el-form-item>
            <el-form-item label="重点科室">
              <el-checkbox-group v-model="categoryForm.info.importantClass" class="checkbox-wrap">
                <el-checkbox v-for="item in importantDepartList" :key="item.dataValue" :label="item.dataValue">{{item.dataKey}}</el-checkbox>
              </el-checkbox-group> 
            </el-form-item>
            <el-form-item label="院内地址">
              <el-input v-model="categoryForm.info.address" placeholder="如：门诊楼3楼401室" style="width: 500px;" />
            </el-form-item>
            <el-form-item label="科室电话">
              <el-input v-model="categoryForm.info.phone" placeholder="如：028-888888888" style="width: 500px;" />
            </el-form-item>
          </div>
          <!-- 院区设置 -->
          <div class="setting-card" v-if="categoryForm.type == 11">
            <el-form-item label="院区地址">
              <el-input v-model="categoryForm.info.areaAddress" placeholder="如：静沙南路18号沙河中心B座七层" style="width: 500px;" />
            </el-form-item>
            <el-form-item label="院区电话">
              <el-input v-model="categoryForm.info.areaPhone" placeholder="如：400-888-8888" style="width: 500px;" />
            </el-form-item>
            <el-form-item label="院区坐标">
              <el-input v-model="categoryForm.info.areaPoint" placeholder="如：104.083333,30.666667" style="width: 500px;" />
            </el-form-item>
          </div>
        </div>
      </div>
    </el-form>
    <!-- 图片上传 -->
    <FilesUpload v-model:showDialog="showBackImageUpload" :limit="1" @getFileList="handleGetCoverImg"/>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, nextTick } from 'vue'
import { useStore } from 'vuex'
import { getAllCategory, insertCategory, updateCategory, getCategoryDetail } from '@/api/category'
import { selectTemplateList } from '@/api/template'
import { selectAllModel } from '@/api/model'
import { selectListDict } from "@ruifox-cms/utils"
import { getProcessList } from "@/api/workflow"
import { pinyin } from 'pinyin-pro'
import { Plus, Delete } from '@element-plus/icons-vue'
import { ElMessage } from "element-plus"
import { createTreeData } from '@ruifox-cms/utils'

const store = useStore()
const parentCategory = ref({}) // 上级栏目详情
const siteId = computed(() => store.state.site.currentSite?.id)
const categoryId = computed(() => store.state.category.categoryId)
const categoryPid = computed(() => store.state.category.categoryPid)
// 栏目类型选项(icon资源在assets中)
const categoryTypeList = computed(() => store.state.category.categoryType)
// 获取特色科室选项
const specialDepartList = ref([])
const getSpecialDepart = async () => {
  const res = await selectListDict({ dictionaryGroupId: 16 })
  if (res.code === 20000) {
    specialDepartList.value = res.data
  }
}
getSpecialDepart()
// 获取重点科室选项
const importantDepartList = ref([])
const getImportantDepart = async () => {
  const res = await selectListDict({ dictionaryGroupId: 17 })
  if (res.code === 20000) {
    importantDepartList.value = res.data
  }
}
getImportantDepart()
// 栏目类型切换
const handleChangeType = (val) => {
  const type = categoryTypeList.value.find(item => item.dataValue === val)
  // 除了单页和列表详情类，其余不需要审核流和模型
  if (![1, 2].includes(type.dataValue)) {
    categoryForm.procdefId = null
    categoryForm.modelId = -1
  }
  categoryForm.icon = type.description
}
// 获取模板选项
const headTemplateList = ref([])
const getHeadTemplateList = () => {
  selectTemplateList({type: 5}).then(res => {
    headTemplateList.value = res.data
  })
}
getHeadTemplateList()
const footTemplateList = ref([])
const getFootTemplateList = () => {
  selectTemplateList({type: 6}).then(res => {
    footTemplateList.value = res.data
  })
}
getFootTemplateList()
const pageTemplateList = ref([])
const getPageTemplateList = () => {
  selectTemplateList({type: 2}).then(res => {
    pageTemplateList.value = res.data
  })
}
getPageTemplateList()
const detailTemplateList = ref([])
const getDetailTemplateList = () => {
  selectTemplateList({type: 3}).then(res => {
    detailTemplateList.value = res.data
  })
}
getDetailTemplateList()
// 获取内容模型选项
const modelList = ref([])
const _getModelList = () => {
  selectAllModel().then(res => {
    modelList.value = res.data
  })
}
_getModelList()
// 获取内已发布流程
const processList = ref([])
const _getProcessList = () => {
  getProcessList().then(res => {
    processList.value = res.data
  })
}
_getProcessList()
// 获取栏目树
const treeData = ref([])
const treeProps = reactive({
  label: 'name',
  value: 'id',
  children: 'children',
  checkStrictly: true,
  expandTrigger: 'hover',
  emitPath: false,
  disabled: (data) => {
    return data.id == categoryId.value || [1, 2, 3, 5, 10].includes(data.type)
  }
})
const shadowTreeProps = reactive({
  label: 'name',
  value: 'id',
  children: 'children',
  checkStrictly: true,
  expandTrigger: 'hover',
  emitPath: false
})
const _getAllCategory = async () => {
  let res = {}
  try {
    res = await getAllCategory({siteId: siteId.value})
  } catch (error) {
    res = {code: 20000, data: []}
  }

  if (res.code === 20000) {
    treeData.value = createTreeData(res.data)
    treeData.value.unshift({name: '根栏目', id: 0, type: 'root'})
    const pid = categoryPid.value
    if(pid || pid === 0){
      const parentData = res.data.find(item => item.id == pid) || {name: '根栏目', id: 0, type: 'root'}
      handleChooseParent(parentData)
    }
  }
}
_getAllCategory()
// 添加栏目
const categoryFormRef = ref(null)
const categoryForm = reactive({
  groupId: null,
  siteId: store.state.site.currentSite?.id,
  isChannel: false,
  level: null,
  modelId: null,
  name: "",
  pid: null,
  parentString: "",
  headTemplate: null,
  footTemplate: null,
  detailTemplate: null,
  pageTemplate: null,
  type: null,
  uri: '',
  icon: '',
  backImage: null,
  state: 0,
  navIcon: '',
  info: {},
  link: '',
  originId: null
})
const uriValidate = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请输入栏目路径'))
    return
  }
  // 允许以/开头,后面只能包含字母数字下划线
  const regex = /^\/[a-zA-Z0-9_]+$/
  if (!regex.test(value)) {
    callback(new Error('栏目路径只能以/开头,后面只能包含字母、数字和下划线'))
    return
  }
  callback()
}
const categoryFormRules = reactive({
  pid: [
    { required: true, message: '请选择上级栏目', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入栏目名称', trigger: 'blur' }
  ],
  uri: [
    { required: true, validator: uriValidate, trigger: 'change' }
  ],
  type: [
    { required: true, message: '请选择栏目类型', trigger: 'blur' }
  ]
})
// 选择上级栏目后，自动生成uri
const firstName = ref('')
const handleChooseParent = (data) => {
  if(data.id == categoryId.value || [1, 2, 3, 5, 10].includes(data.type)) return
  parentCategory.value = structuredClone(data)
  // 站点首页、站点子站下的栏目的level从新开始计算
  if (data.type === 'root' || data.type == 3 || data.type == 8) {
    categoryForm.level = 1
  } else {
    categoryForm.level = data.level + 1
  }
  categoryForm.pid = data.id
  if(data.uri) {
    firstName.value = data.uri + '_'
  } else {
    firstName.value = '/'
  }
  handleBlurName()
}
const secondName = computed(() => {
  // 如果名称是空的，返回空字符串
  if (!categoryForm.name) return ''
  
  // 首先移除所有特殊字符，并将空格替换为下划线
  const cleanName = categoryForm.name.replace(/[^\p{L}\p{N}\s_]/gu, '').replace(/\s+/g, '_')
  
  // 判断是否包含中文字符
  const hasChinese = /[\u4e00-\u9fa5]/.test(cleanName)
  
  if (hasChinese) {
    // 如果是中文，使用拼音逻辑
    return pinyin(cleanName, {pattern: 'first', toneType: 'none', type: 'array'}).join('')
  } else {
    // 如果是英文，转为小写
    const lowerName = cleanName.toLowerCase()
    
    // 如果长度超过50，则取每个单词的首字母
    if (firstName.value.length + lowerName.length > 20) {
      return lowerName
        .split('_')
        .map(word => word.charAt(0))
        .join('')
    }
    
    // 否则直接返回处理后的名称
    return lowerName
  }
})
const handleBlurName = () => {
  categoryForm.uri = firstName.value + secondName.value
}
// 获取栏目信息
const _getCategoryDetail = async () => {
  const res = await getCategoryDetail({ id: categoryId.value, groupId: null })
  if (res.code === 20000) {
    Object.assign(categoryForm, res.data)
    if (!res.data.info) {
      categoryForm.info = {}
    }
  }
}
// 获取栏目拼音首字母
const getFirstLetter = (str) => {
  const pinyinArray = pinyin(str, {style: pinyin.STYLE_FIRST_LETTER})
  return pinyinArray[0].toUpperCase()
}
// 提交栏目表单,成功后返回上级路由
const submitCategoryForm = async () => {
  return new Promise(resolve => {
    categoryFormRef.value.validate(valid => {
      if (valid) {
        if(categoryForm.type === 9){
          categoryForm.info.pinyin = getFirstLetter(categoryForm.name)
        }
        if(!categoryForm.headTemplate && !categoryForm.footTemplate){
          categoryForm.headTemplate = parentCategory.value.headTemplate
          categoryForm.footTemplate = parentCategory.value.footTemplate
        }
        // 更新
        if (categoryForm.id) {
          updateCategory(categoryForm).then(async res => {
            if (res.code === 20000) {
              ElMessage({
                message: '更新成功',
                type: 'success'
              })
            }
            await store.dispatch('category/updateCategory')
            store.commit('category/SET_CATEGORY_DRAWER', false)
            resolve(true)
          })
        } else {
          // 新增
          insertCategory(categoryForm).then(async res => {
            if(res.code === 20000){
              categoryForm.id = res.data
              ElMessage.success('创建成功, 请添加模板')
            }
            await store.dispatch('category/updateCategory')
            resolve(true)
          })
        }
      }
    })
  })
}

// 上传图片
const showBackImageUpload = ref(false)
const uploadField = ref('')
const handleUpload = (field) => {
  uploadField.value = field
  showBackImageUpload.value = true
}

const handleGetCoverImg = (imgList) => {
  categoryForm[uploadField.value] = imgList[0].url
}
// 移除图片
const handleRemoveImg = (key) => {
  categoryForm[key] = ''
}
// 获取内容分类
const contentClasses = computed(() => {
  return modelList.value.find(item => item.id === categoryForm.modelId)?.contentClasses || []
})
// 改变内容模型
const handleChangeModel = () => {
  categoryForm.info.class = []
}
// 选择调用其他栏目数据
const handleChooseOrigin = (data) => {
  categoryForm.originId = data.id
}

// 标签输入
const tagInputVisible = ref(false)
const tagInputValue = ref('')
const tagInputRef = ref(null)
const handleTagInput = () => {
  tagInputVisible.value = true
  nextTick(() => {
    tagInputRef.value.input.focus()
  })
}
const handleTagConfirm = () => {
  categoryForm.info.tags ? '' : categoryForm.info.tags = []
  if (tagInputValue.value) {
    categoryForm.info.tags.push(tagInputValue.value)
    tagInputValue.value = ''
  }
  tagInputVisible.value = false
}
const handleClose = (tag) => {
  categoryForm.info.tags = categoryForm.info.tags.filter(item => item !== tag)
}

onMounted(async () => {
  if(categoryId.value){
    _getCategoryDetail()
  }
  if(categoryPid.value){
    categoryForm.pid = Number(categoryPid.value)
  }
})
defineExpose({
  submitCategoryForm
})
</script>

<style lang='scss' scoped>
.category-setting {
  .setting-card {
    margin-bottom: 12px;
    border: 1px solid #e6e6e6;
    border-radius: 4px;

    .card-header {
      padding: 10px 15px;
      background-color: #f5f7fa;
      font-weight: bold;
      font-size: 14px;
      border-bottom: 1px solid #e6e6e6;
      color: #333;
    }

    .card-body {
      padding: 12px 15px;
      
      .el-form-item {
        margin-bottom: 14px;
        
        &:last-child {
          margin-bottom: 0;
        }
      }
    }
  }

  .checkbox-wrap {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    max-width: 700px;
  }
}

.form-img {
  height: 100px;
  width: 150px;
  border: 1px dashed $borderColor;
  cursor: pointer;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 2px;

  .has-img {
    height: 100%;
    width: 100%;
    position: relative;
    display: flex;
    justify-content: center;
    align-items: center;

    img {
      max-width: 100%;
      max-height: 100%;
      object-fit: contain;
    }

    span {
      display: none;
      position: absolute;
      right: 0;
      top: 0;
      background-color: $failColor;
      height: 20px;
      width: 20px;
      font-size: 18px;
      color: #fff;
    }

    &:hover {
      span {
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }
  }
}
</style>